<template>
  <basic-container>
    <el-alert
      title="统计时间：可查询最近三个月的信息"
      type="warning"
      :closable="false"
      style="margin-bottom: 10px"
    >
    </el-alert>
    <avue-crud
      :option="option"
      :search.sync="search"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @sort-change="sortChange"
    >
      <!-- @on-load="onLoad" -->
      <template slot="menuLeft">
        <div class="curd-foter">
          <div class="redFontBox">
            奖励金额汇总：<span class="redFont">{{
              exhibition(countData.totalAmount) || 0
            }}</span>
            元
          </div>
        </div>
      </template>
      <template slot="menuRight">
        <el-button type="primary" size="small" @click="setTime('今天')"
          >今天
        </el-button>
        <el-button type="primary" size="small" @click="setTime('昨天')"
          >昨天
        </el-button>
        <el-button type="primary" size="small" @click="setTime('本月')"
          >本月
        </el-button>
        <el-button
          type="warning"
          size="small"
          plain
          icon="el-icon-download"
          v-if="permissionList.exportBtn"
          @click="handleExport"
          >导出
        </el-button>
      </template>
      
      <!-- <template slot-scope="{}" slot="accountManagerSearch">
        <select-page
          ref="searchKhjlSelect"
          label="accountManagerName"
          value="accountManager"
          :select.sync="search.accountManager"
          :url="website.searchLink.accountManager"
          placeholder-text="客户经理"
          filter-key="searchParam"
        ></select-page>
      </template>
      <template slot-scope="{}" slot="orgNoSearch">
        <select-page ref="searchOrgSelect" label="serviceName" value="serviceNo" :select.sync="search.orgNo" :url="website.searchLink.orgUrl" placeholder-text="机构" filter-key="searchParam"></select-page>
      </template>
      <template slot-scope="{}" slot="serviceNoSearch">
        <select-page
          ref="searchSerSelect"
          label="serviceName"
          value="serviceNo"
          :select.sync="search.serviceNo"
          :url="website.searchLink.serviceUrl"
          placeholder-text="服务商"
          filter-key="searchParam"
        ></select-page>
      </template> -->
      <template slot-scope="{}" slot="rpiNoSearch">
        <select-page
          ref="searchRpiSelect"
          label="rpiName"
          value="rpiNo"
          :select.sync="search.rpiNo"
          :url="website.searchLink.merchantUrl"
          placeholder-text="商户"
          filter-key="searchParam"
        ></select-page>
      </template>
      <template slot-scope="{}" slot="storeNoSearch">
        <select-page ref="searchRpsSelect" label="rpsName" value="rpsNo" :select.sync="search.storeNo" :url="website.searchLink.rpsUrl" placeholder-text="门店" filter-key="searchParam"></select-page>
      </template>
      
      <template slot-scope="{disabled,size}" slot="beginTimeSearch">
        <el-date-picker v-model="search.beginTime" type="datetime" value-format='yyyy-MM-dd HH:mm:ss' @change="beginTimeChange" placeholder="请输入 扣费开始日期"></el-date-picker>
      </template>
      <template slot-scope="{disabled,size}" slot="endTimeSearch">
        <el-date-picker v-model="search.endTime" type="datetime" default-time="23:59:59" value-format='yyyy-MM-dd HH:mm:ss' @change="endTimeChange" placeholder="请输入 扣费结束日期"></el-date-picker>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import { getList, getListCount, getExport } from "@/api/rb-oem/active/flowCard";
import { mapGetters } from "vuex";
import { dateFormat } from "@/util/date";
import { downloadFileExcel } from "@/util/util";
import selectPage from "@/components/select-page/select-page";

export default {
  components: {
    selectPage
  },
  data() {
    return {
      form: {},
      query: {
        beginTime: dateFormat(new Date(), "yyyy-MM") + "-01 00:00:00",
        endTime: dateFormat(new Date(), "yyyy-MM-dd") + " 23:59:59",
      },
      search: {
        beginTime: dateFormat(new Date(), "yyyy-MM") + "-01 00:00:00",
        endTime: dateFormat(new Date(), "yyyy-MM-dd") + " 23:59:59",
      },
      loading: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: "calc(50vh - 50px)",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        viewBtn: false,
        editBtn: false,
        addBtn: false,
        delBtn: false,
        selection: true,
        searchMenuSpan: 24,
        columnBtn: false,
        labelWidth: 170, //弹出表单的标题的统一宽度
        searchLabelWidth: 100, //搜索框标题宽度
        menu:false,
        menuWidth: 100, //操作栏宽度
        // searchIcon:true,
        // searchIndex:3,
        emptyBtnText:'重置',
        column: [
          // {
          //   label: "服务商编号",
          //   searchLabel: "服务商",
          //   prop: "serviceNo",
          //   type: "select",
          //   search: true,
          //   searchOrder: 2,
          //   span: 24,
          //   overHidden: true,
          //   width: 110
          // },
          // {
          //   label: "服务商名称",
          //   prop: "serviceName",
          //   type: "input",
          //   minWidth: 200
          // },
          // {
          //   label: "",
          //   prop: "isSelectChild",
          //   type: "select",
          //   multiple: false,
          //   dataType: "string",
          //   showColumn: false,
          //   hide: true,
          //   display: false,
          //   search: true,
          //   searchType: "checkbox",
          //   searchSpan: 0,
          //   searchLabelWidth: "0",
          //   searchOrder: 2,
          //   dicData: [
          //     {
          //       label: "包含下级",
          //       value: 1
          //     }
          //   ]
          // },
          // {
          //   label: "机构编号",
          //   prop: "orgNo",
          //   type: "input",
          //   overHidden: true,
          //   search: true,
          //   searchOrder: 0,
          //   minWidth:200
          // },
          // {
          //   label: "机构名称",
          //   prop: "orgName",
          //   type: "input",
          //   overHidden: true,
          //   minWidth:200
          // },
          // {
          //   label: "客户经理编号",
          //   prop: "accountManager",
          //   type: "input",
          //   overHidden: true,
          //   search: true,
          //   searchOrder: 1,
          //   width: 110
          // },
          // {
          //   label: "客户经理名称",
          //   prop: "accountManagerName",
          //   type: "input",
          //   overHidden: true,
          //   width: 100
          // },
          {
            label: "商户分类",
            prop: "merchantTypeName",
            overHidden:true,
            width: 80
          },
          {
            label: "商户分类",
            prop: "merchantType",
            type: "select",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            dataType: "number",
            dicUrl: "/api/blade-system/dict/dictionary?code=merchant_type",
            search: true,
            overHidden: true,
            minWidth:80,
            searchOrder: 6,
            display:false,
            hide:true
          },
          {
            label: "商户编号",
            searchLabel: "商户",
            prop: "rpiNo",
            type: 'select',
            width: 140,
            display: false,
            search: true,
            overHidden:true,
            searchOrder: 1
          },
          {
            label: "商户注册名称",
            prop: "registeredName",
            type: "input",
            // search: true,
            display:false,
            width: 200,
            searchOrder: 1
          },
          {
            label: "门头名称",
            prop: "rpiName",
            type: "input",
            width: 200,
            search: true,
            searchOrder: 1
          },
          {
            label: "商户简称",
            prop: "userShortName",
            type: "input",
            search: true,
            overHidden: true,
            width: 200,
            display:false,
            searchOrder: 3
          },
          
          {
            label: "门店编号",
            searchLabel: "门店",
            prop: "storeNo",
            type: "input",
            search: true,
            searchOrder: 4,
            minWidth: 140,
            overHidden:true,
            display:false,
            hide:true
          },
          {
            label: "门店名称",
            prop: "storeName",
            type: "input",
            minWidth: 170,
            overHidden:true,
            display:false
          },
          {
            label: "SN编号",
            searchLabel:"交易SN编号",
            prop: "sn",
            type: "input",
            search: true,
            searchOrder: 7,
            minWidth: 140,
            overHidden:true
          },
          {
            label: "物联网ID",
            prop: "simId",
            type: "input",
            search: true,
            searchOrder: 8,
            minWidth: 140,
            overHidden:true
          },
          {
            label: "活动编号",
            prop: "activeCode",
            type: "select",
            minWidth: 140,
            overHidden:true,
          },
          {
            label: "活动名称",
            prop: "activeName",
            type: "select",
            minWidth: 140,
            overHidden:true,
          },
          {
            label: "物联网扣费日期",
            prop: "createTime",
            type: "select",
            minWidth: 140,
            overHidden:true,
          },
          {
            label: "物联网扣费次数",
            prop: "debitCount",
            type: "select",
            minWidth: 140,
            overHidden:true,
          },
          {
            label: "物联网扣费金额",
            prop: "simAmount",
            type: "select",
            minWidth: 140,
            overHidden:true,
          },
          {
            label: "服务商奖励金额",
            prop: "rewardAmount",
            type: "input",
            overHidden:true,
            searchOrder: 12,
            minWidth:120
          },
          {
            label: "实际入账金额",
            prop: "realAmount",
            type: "input",
            overHidden: true,
            width:110
          },
          {
            label: "通道名称",
            prop: "aisleName",
            type: "input",
            overHidden:true,
            searchOrder: 12,
            minWidth:70
          },
          {
            label: "通道名称",
            prop: "aisleKind",
            type: "select",
            // dataType: "number",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            dicUrl: "/api/blade-system/dict/dictionary?code=aisle_kind",
            formslot:true,
            overHidden:true,
            search: true,
            hide:true,
            searchOrder: 17,
            minWidth: 92
          },
          {
            label: "结算类型",
            prop: "settlementModeName",
            type: "input",
            overHidden:true,
            minWidth:92
          },
          // {
          //   label: "结算类型",
          //   prop: "settlementMethod",
          //   type: "select",
          //   // dataType: "number",
          //   props: {
          //     label: "dictValue",
          //     value: "dictKey"
          //   },
          //   dicUrl: "/api/blade-system/dict/dictionary?code=settlement_method",
          //   formslot:true,
          //   overHidden:true,
          //   minWidth: 92
          //   // search: true,
          //   // searchOrder: 1
          // },
          // {
          //   label: "统计日期",
          //   prop: "timeData",
          //   type: "datetimerange",
          //   searchRange: true,
          //   defaultTime:['00:00:00', '23:59:59'],
          //   format: "yyyy-MM-dd HH:mm:ss",
          //   valueFormat: "yyyy-MM-dd HH:mm:ss",
          //   startPlaceholder: "统计日期开始时间",
          //   endPlaceholder: "统计日期结束时间",
          //   search: true,
          //   rules: [
          //     {
          //       required: true,
          //       message: "请选择统计日期",
          //       trigger: "blur",
          //     },
          //   ],
          //   hide: true,
          //   searchSpan: 12,
          //   display: false
          // },
          {
            label: "扣费开始日期",
            prop: "beginTime",
            type: "input",
            search: true,
            hide: true,
            display: false
          },
          {
            label: "扣费结束日期",
            prop: "endTime",
            type: "input",
            search: true,
            hide: true,
            display: false
          }
        ]
      },
      data: [],
      countData: {},
      selectType: 1, // 1:本级 2:机构 3:服务商
      simQueryType: 1 // 流量卡查询类型 1.明细 2.流水
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        viewBtn: this.vaildData(this.permission.self_active_flowCard_view, false),
        exportBtn: this.vaildData(this.permission.self_active_flowCard_export,false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    exhibition() {
      return (val) => {
        if (val == "" || val == undefined) {
          return (val = 0);
        } else {
          return val;
        }
      };
    }
  },
  watch: {
    // "search.timeData"(val){
    //   if(val){
    //     this.search.beginTime = val[0];
    //     this.search.endTime = val[1];
    //   }else{
    //     this.search.beginTime = "";
    //     this.search.endTime = "";
    //   }
    // }
  },
  methods: {
    beginTimeChange() {
      if(this.search.endTime){
        if(Date.parse(this.search.beginTime) > Date.parse(this.search.endTime)){
          this.$alert('统计开始日期不能大于结束日期', '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          })
          .then(() => (this.search.beginTime = ""))
          .catch(() => (this.search.beginTime = ""))
        }
      }
    },
    endTimeChange() {
      if(this.search.beginTime){
        if(Date.parse(this.search.endTime) < Date.parse(this.search.beginTime)){
          this.$alert('统计结束日期不能小于开始日期', '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          })
          .then(() => (this.search.endTime = ""))
          .catch(() => (this.search.endTime = ""))
        }
      }
    },
    setTime(type) {
      let date = new Date();
      this.query = {};
      if (type == "今天") {
        this.search.beginTime = dateFormat(date, "yyyy-MM-dd") +' 00:00:00';
        this.search.endTime = dateFormat(date, "yyyy-MM-dd") +' 23:59:59';
        // this.search.timeData = [this.search.beginTime, this.search.endTime];
        this.page.currentPage = 1;
        this.forInSearch()
        this.refreshChange();
      } else if (type == "昨天") {
        this.search.beginTime = dateFormat(new Date(date.getTime() - 3600 * 1000 * 24 * 1),"yyyy-MM-dd")+' 00:00:00';
        this.search.endTime = dateFormat(new Date(date.getTime() - 3600 * 1000 * 24 * 1),"yyyy-MM-dd")+' 23:59:59';
        // this.search.timeData = [this.search.beginTime, this.search.endTime];
        this.page.currentPage = 1;
        this.forInSearch()
        this.refreshChange();
      } else {
        // "本月"
        this.search.beginTime = dateFormat(date,"yyyy-MM")+'-01 00:00:00';
        this.search.endTime = dateFormat(date,"yyyy-MM-dd")+' 23:59:59';
        // this.search.timeData = [this.search.beginTime, this.search.endTime];
        this.page.currentPage = 1;
        // this.query.beginTime = this.search.beginTime;
        // this.query.endTime = this.search.endTime;
        // this.query.timeData = this.search.timeData;
        this.forInSearch()
        this.refreshChange();
      }
    },
    forInSearch(){
      for(let key in this.search){
        //console.log(key)
        if(this.search[key]){
          if(key.indexOf("$") == -1 ){
            this.query[key] = this.search[key]
          }
        }
      }
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        //   getDetail(this.form.id).then(res => {
        //     this.form = res.data.data;
        //   });
      }
      done();
    },
    searchReset() {
      // this.$set(this.search, 'timeData', ["",""])
      this.query = {};
      // this.search = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      // console.log(111111111)
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      // this.refreshChange()
      this.onLoad(this.page, this.query);
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      // this.refreshChange()
      this.onLoad(this.page, this.query);
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      let addObj = {
        selectType: this.selectType,
        simQueryType:this.simQueryType
      };
      /* 表格 */
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query, addObj)
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });

      /* 获取统计 */
      getListCount(Object.assign(params, this.query, addObj)).then((res) => {
        this.countData = res.data.data;
      });
    },
    handleExport() {
      // let params = {
      //   ...this.search,
      //   current: "-1",
      //   size: "-1",
      // };
      // params.selectType = this.selectType;
      // params.simQueryType = this.simQueryType;

      this.$confirm("是否导出用户数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.forInSearch()
        this.query.selectType = this.selectType;
        this.query.simQueryType = this.simQueryType;
        getExport(this.query).then((res) => {
          console.log(res)
            // downloadFileExcel(res);
            this.$message({
              type: "success",
              message: res.data.msg
            });
          },
          (error) => {
            window.console.log(error);
          }
        );
      });
    },
    sortChange(val) {
      if (val.order == "ascending") {
        //正序
        this.query.ascs = val.prop;
        this.query.descs = "";
      } else {
        //倒序
        this.query.descs = val.prop;
        this.query.ascs = "";
      }
      this.refreshChange();
    }
  }
};
</script>

<style lang="scss" scoped>
.curd-foter {
  padding-top: 10px;
  display: flex;
  flex-wrap: wrap;
}

.redFontBox {
  margin-right: 40px;
  .redFont {
    color: red;
  }
}
</style>
